import { defineStore } from 'pinia'
import { ref } from 'vue'
import useLineStore from './useLineStore'

const scale = ref(0.5)

export default defineStore('config', () => {
  const config = ref<CanvasConfig>()
  const lineStore = useLineStore()

  let imgContainer: HTMLDivElement
  async function getConfig(id: number, container?: HTMLDivElement) {
    if (container) {
      imgContainer = container
    }

    await lineStore.find(id)
    const { maxX, maxY, minY } = lineStore.line!

    const scaleStep = 50
    const margin = {
      top: 100,
      bottom: 100,
      left: 100,
      right: 100,
    }
    const startY = Math.floor(minY / 50 - 1) * 50

    // 计算宽度
    const offsetWidth = imgContainer.offsetWidth || 0

    let width = Math.ceil((maxX * scale.value) / scaleStep) * scaleStep + margin.left + margin.right
    width = Math.max(width, offsetWidth)

    // 计算高度
    const offsetHeight = imgContainer.offsetHeight || 0
    let height =
      Math.ceil((maxY * scale.value - startY * scale.value) / scaleStep) * scaleStep + margin.top + margin.bottom
    height = Math.max(height, offsetHeight)

    config.value = {
      width,
      height,
      startY,
      scaleStep,
      margin,
      scale: scale.value,
    }
  }
  return { getConfig, config, scale }
})
